﻿using Application.Adapter;
using Application.Common.Extensions;
using Domain;
using Domain.Models;
using Domain.Options;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using TouchSocket.Core;
using TouchSocket.Sockets;

namespace Application.Plugins
{
    public class DisconnectedPlugin : ITcpDisconnectedPlugin<ISocketClient>
    {
        private readonly IHttpClientFactory _httpClientFactory;

        private readonly ApiConfigOptions apiConfigOptions;
        public DisconnectedPlugin(IHttpClientFactory httpClientFactory,IOptions<ApiConfigOptions> apiConfigOption)
        {
            _httpClientFactory = httpClientFactory;
            apiConfigOptions = apiConfigOption.Value;
        }
        public int Order { get => 1; set => this.Order = value; }

        public void Dispose()
        {

        }

        public void Loaded(IPluginsManager pluginsManager)
        {

        }

        /// <summary>
        /// 当链接的socket断开时候才会执行，设备断开并不会触发
        /// </summary>
        /// <param name="client"></param>
        /// <param name="e"></param>
        /// <returns></returns>
        public async Task OnTcpDisconnected(ISocketClient client, DisconnectEventArgs e)
        {
            Consts.DeviceToSocketId.TryGetKey(client.Id, out var deviceId);
            Console.WriteLine($"{client.GetIPPort()}连接的{deviceId}设备断开");
            if (string.IsNullOrEmpty(deviceId) || !Consts.devices.ContainsKey(deviceId))
                return;
            Consts.devices[deviceId].State = 0;

            using var httpClient = _httpClientFactory.CreateClient();
            try
            {
                var data = new DeviceStateCall { state = 0,device=deviceId };
                httpClient.BaseAddress = new Uri(apiConfigOptions.BaseCallBackUrl);
                await httpClient.PostAsync(apiConfigOptions.StateUpdateUrl, new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"));
            }
            catch (Exception)
            {
                await Console.Out.WriteLineAsync("设备断开回调失败");
            }
            return;
        }
    }
}
